package com.moleq.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

public class ServiceUtil {
	private static final String TAG = "FileProcessor";

	public static String convertToRptDate(String val){
		return val.replace("-", "");
	}
	
	public static String getCurrentDateTime(){
		SimpleDateFormat   formatter   =   new   SimpleDateFormat   ("yyyy-MM-dd hh:mm:ss");     
		Date   curDate   =   new   Date(System.currentTimeMillis());//閿熸枻鎷峰彇閿熸枻鎷峰墠鏃堕敓鏂ゆ嫹     
		String   str   =   formatter.format(curDate);   
		  
		return str;
	}
	
	public static String getCurrentDateTimeNow(){
		SimpleDateFormat   formatter   =   new   SimpleDateFormat   ("yyyyMMddhhmmss");     
		Date   curDate   =   new   Date(System.currentTimeMillis());//閿熸枻鎷峰彇閿熸枻鎷峰墠鏃堕敓鏂ゆ嫹     
		String   str   =   formatter.format(curDate);   
		  
		return str;
	}
	
	public static List<String> getExtraFiles(String fileName) {
		List<String> result = new ArrayList<String>();
		File file = new File(fileName);

		if (file.exists()) {
			String read;
			FileReader filereader;
			BufferedReader bufreader = null;
			try {
				filereader = new FileReader(file);
				bufreader = new BufferedReader(filereader);
				try {

					while ((read = bufreader.readLine()) != null) {
						Log.e(TAG, "--->> read line ---->> " + read);

						String temp[] = read.split(",");

						for (int i = 0; i < temp.length; i++) {
							String tmp = getTagValue(temp[i], "file");
							if (!tmp.equals("")) {
								result.add(tmp);
							}
						}
					}

					filereader.close();
					bufreader.close();
				} catch (IOException e) {
				}
			} catch (FileNotFoundException e) {
			}

		}

		return result;
	}

	public static byte[] convertImageFile2Bytes(String path) {

		byte[] bytes = null;
		try {

			FileInputStream fs = new FileInputStream(path);
			BufferedInputStream bs = new BufferedInputStream(fs);
			Bitmap btp = BitmapFactory.decodeStream(bs);

			bs.close();
			fs.close();

			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			btp.compress(CompressFormat.JPEG, 100, baos);
			bytes = baos.toByteArray();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return bytes;
	}

	public static String getTagValue(String str, String tag) {
		String result = "";
		String start, end;
		int i, j;

		if (str.equals("") || tag.equals(""))
			return result;

		start = "[" + tag + "]";
		end = "[/" + tag + "]";

		i = str.indexOf(start);
		j = str.indexOf(end);
		if (i >= 0 && j >= 0) {
			result = str.substring(i + start.length(), j);
		}

		return result;

	}

	public static List<String> getRecords(String fileName) {

		List<String> result = new ArrayList<String>();
		File file = new File(fileName);

		if (file.exists()) {
			String read;
			FileReader filereader;
			BufferedReader bufreader = null;
			try {
				filereader = new FileReader(file);
				bufreader = new BufferedReader(filereader);
				while ((read = bufreader.readLine()) != null) {
					if (!read.trim().equals("")) {
						result.add(read);
					}
				}
				filereader.close();
				bufreader.close();
			} catch (Exception e) {
				result.clear();
			}

		}

		return result;

	}

	public static String getEntryNumInFile(String str) {
		String result = "";
		int i, j;

		if (str == null || str.equals(""))
			return result;

		String tmp = "";

		i = str.indexOf("{");
		j = str.indexOf("}");

		if (i >= 0 && j > i) {
			result = str.substring(i + 1, j);
		}

		return result;
	}

	public static String getNewEntryNum() {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssssss");
		return formatter.format(new Date());
	}

	public static HashMap<Integer, String> parseFileName(String fileName) {

		HashMap<Integer, String> result = new HashMap<Integer, String>();
		String tmp = fileName;

		int i, j;
		Integer cnt = 0;

		do {

			i = tmp.indexOf("{");
			j = tmp.indexOf("}");

			if (i >= 0 && j > i) {
				result.put(cnt++, tmp.substring(i + 1, j));
				tmp = tmp.substring(j + 1);
			}

		} while (i >= 0 && j > i);

		return result;
	}

	public static void copyFile(String fileFromPath, String fileToPath) throws Exception {
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new FileInputStream(fileFromPath);
			out = new FileOutputStream(fileToPath);
			int length = in.available();
			int len = (length % 1024 == 0) ? (length / 1024) : (length / 1024 + 1);
			byte[] temp = new byte[1024];
			for (int i = 0; i < len; i++) {
				in.read(temp);
				out.write(temp);
			}
		} finally {
			if (in != null)
				in.close();
			if (out != null)
				out.close();
		}
	}

	public static boolean Move(String srcFile, String destPath) {
		// File (or directory) to be moved
		File file = new File(srcFile);

		// Destination directory
		File dir = new File(destPath);

		// Move file to new directory
		boolean success = file.renameTo(new File(dir, file.getName()));

		return success;
	}

	public static ArrayList<String> parseSqlRecord(String str) {
		ArrayList<String> newStrings = new ArrayList<String>();
		boolean bContinue = false;
		String[] temps = str.split(",");
		String value = "";
		int part = 0;
		for (int i = 0; i < temps.length; i++) {
			int j = 0;
			String str1 = temps[i];

			if (str1.length() > 0) {
				String first = "";
				String end = "";

				if (!bContinue) {
					first = str1.trim().substring(0, 1);
					if (first.equals("'")) {
						bContinue = true;
						part = 1;
					}
				}

				if (bContinue) {

					value += str1;

					String str2 = str1.trim();
					int count = 0;
					int k = 0;
					j = str2.length();

					do {
						if (part > 1) {
							k = 0;
						} else {
							k = 1;
						}
						end = str2.substring(j - 1, j);
						if (end.equals("'")) {
							count++;
							j--;
						} else {
							j = 0;
						}

					} while (j > k);

					if (count % 2 == 1) {
						newStrings.add(value);
						value = "";
						bContinue = false;
						part = 0;
					} else {
						value += ",";
						part++;
					}
				} else {
					newStrings.add(str1);
				}
			}
		}
		return newStrings;
	}

	public static String getLocalIpAddress() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException ex) {
			Log.e("WifiPreference IpAddress", ex.toString());
		}
		return null;
	}

	private static String getLocalMacAddress() {
		String result = "";
		String Mac = "";
		result = callCmd("busybox ifconfig", "HWaddr");
		if (result == null) {
			return "NetworkError";
		}

		if (result.length() > 0 && result.contains("HWaddr") == true) {
			Mac = result.substring(result.indexOf("HWaddr") + 6, result.length() - 1);
			Log.i("test", "Mac:" + Mac + " Mac.length: " + Mac.length());
			Log.i("test", result + " result.length: " + result.length());
		}
		return Mac;
	}

	private static String callCmd(String cmd, String filter) {
		String result = "";
		String line = "";
		try {
			Process proc = Runtime.getRuntime().exec(cmd);
			InputStreamReader is = new InputStreamReader(proc.getInputStream());
			BufferedReader br = new BufferedReader(is);

			while ((line = br.readLine()) != null && line.contains(filter) == false) {
				Log.i("test", "line: " + line);
			}

			result = line;
			Log.i("test", "result: " + result);
		} catch (Exception e) {
			//e.printStackTrace();
		}
		return result;
	}

	public static String getMacAddress(Context context) {
		String result = "";
		WifiManager wifi_service = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		if (wifi_service.isWifiEnabled()) {
			WifiInfo wifiinfo = wifi_service.getConnectionInfo();
			result = wifiinfo.getMacAddress();
		} else {
			result = getLocalMacAddress();
		}
		
		if (result.equals("")) {
			result = "NoMAC";
		}else{
			result = result.replace(":", "");
		}

		return result.trim();
	}


}
